﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Ext.Net.MVC;
using Ext.Net;
using PcaWeb.Models;

namespace PcaWeb.Areas.Admin.Controllers
{
    public class RolesController : ControllerAdmin
    {
        public StoreResult GetListRoles(string userName)
        {
            NodeCollection nodes = new NodeCollection();
            string[] roles = Roles.GetAllRoles();
            string[] userRoles = Roles.GetRolesForUser(userName);
            Node nodeRol = null;

            foreach (string itemRol in roles)
            {
                nodeRol = new Node();
                nodeRol.Text = itemRol;
                nodeRol.NodeID = itemRol;
                nodeRol.Leaf = true;

                if (userRoles.Contains<string>(itemRol))
                    nodeRol.Checked = true;
                else
                    nodeRol.Checked = false;

                nodes.Add(nodeRol);
            }

            return this.Store(nodes);
        }

        public Ext.Net.MVC.PartialViewResult FrmRegistrar()
        {
            return new Ext.Net.MVC.PartialViewResult
            {
                ViewName = "FrmRegistrar"
            };
        }

        public ActionResult EliminarRol(string id)
        {
            try
            {
                Roles.DeleteRole(id, true);
                return this.RemoteTree(true);
            }
            catch (Exception ex)
            {
                return this.RemoteTree(false, ex.Message);
            }
        }

        [HttpPost]
        public ActionResult RegistrarRol(string roleName)
        {
            try
            {
                if (!string.IsNullOrEmpty(roleName))
                {
                    if (!Roles.RoleExists(roleName))
                        Roles.CreateRole(roleName);

                    return Json(new { success = true });
                }
                else
                {
                    return Json(new { success = false, msg = "\"rolName\" no puede ser un valor NUll" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
    }
}
